import Vue from "vue";
import Router from "vue-router";
import layout from "@/views/Layout/index.vue";
import jwt from "jwt-decode";
import { deepClone } from "@/util/public";
import store from "@/store";

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location: any) {
  return (originalPush as any).call(this, location).catch((err: any) => {
    return err;
  });
};

Vue.use(Router);

/**
 * hidden:true  是否显示
 * name:"" 路由名称 *
 * meta：{
 * title 对应路由左侧菜单栏的标题名称
 * icon 对应路由在左侧菜单栏的图标样式
 * }
 */

const routes: any = [
  {
    path: "/login",
    name: "login",
    meta: { title: "系统登录" },
    component: () => import("@/views/Login/Login.vue"), //按需加载
  },
  {
    path: "/password",
    name: "password",
    meta: { title: "找回密码" },
    component: () => import("@/views/Login/Password.vue"),
  },
  {
    path: "/404",
    name: "404",
    meta: { title: "404" },
    component: () => import("@/views/404.vue"),
  },
  {
    path: "*",
    name: "NotFound",
    meta: { title: "404" },
    component: () => import("@/views/404.vue"),
  },
];

const router: any = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
router.beforeEach(async (to: any, from: any, next: any) => {
  const isLogin = localStorage.spmsToken ? true : false; //是否登录
  if (to.path == "/login" || to.path == "/password") {
    next();
  } else {
    if (isLogin) {
      if (!store.state.hasAuth) {
        await store.dispatch("setUser", localStorage.spmsToken);
        const newRouters = store.state.routers;

        const mainRouter = [
          {
            path: "/",
            name: "dashbord",
            meta: { title: "首页", icon: "fa fa-home" },
            component: layout,
            redirect: "/home",
            children: deepClone(newRouters),
          },
        ];
        router.options.routes = [...mainRouter, ...router.options.routes];
        router.addRoutes(mainRouter);
        next({ path: to.path });
      } else {
        next();
      }
    } else {
      next("/login");
    }
  }
});

router.afterEach((to: any, from: any, next: any) => {
  document.title = to.meta.title;
});

export default router;
